/*
 * SuperLoadingLayout.java
 * business
 *
 * Created by ChenTao on 2017/3/1.
 *
 * Copyright (c) 2017年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.widget.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.IntDef;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yidiandao.business.R;
import com.yidiandao.business.utils.NetworkUtils;
import com.yidiandao.business.utils.UIUtils;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * 统一管理加载中，加载失败，加载为空的Layout.
 */
public class SuperLoadingLayout extends FrameLayout {

    /**
     * 加载中
     */
    public static final int STATE_LOADING = 0;

    /**
     * 空
     */
    public static final int STATE_EMPTY = 1;

    /**
     * 错误
     */
    public static final int STATE_ERROR = 2;

    /**
     * 成功
     */
    public static final int STATE_SUCCESS = 3;

    /**
     * 初始化状态
     */
    public static final int STATE_NONE = 4;

    @IntDef({STATE_LOADING, STATE_EMPTY, STATE_ERROR, STATE_SUCCESS, STATE_NONE})
    @Retention(RetentionPolicy.SOURCE)
    public @interface LoadState {
    }

    private View mLoadingView;

    private View mEmptyView;

    private View mErrorView;

    private View mSuccessView;

    private ImageView mIvLoading;

    private OnStartLoadDataListener mListener;

    private AnimationDrawable mDrawable;

    /**
     * 默认状态为NONE.读取到改状态后,会显示加载中的动画
     */
    private int currentState = STATE_NONE;

    private TextView mTvErrorState;

    private int loadingViewRes, emptyViewRes, errorViewRes;

    public SuperLoadingLayout(Context context) {
        this(context, null);
    }

    public SuperLoadingLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SuperLoadingLayout);
        try {
            loadingViewRes = typedArray.getResourceId(R.styleable.SuperLoadingLayout_loading_view, R.layout.pager_loading);
            emptyViewRes = typedArray.getResourceId(R.styleable.SuperLoadingLayout_empty_view, R.layout.pager_empty);
            errorViewRes = typedArray.getResourceId(R.styleable.SuperLoadingLayout_loading_view, R.layout.pager_error);
        } finally {
            typedArray.recycle();
        }
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        if (isInEditMode()) {
            return;
        }

        setId(R.id.loading_pager);

        if (getChildCount() == 0) {
            throw new IllegalArgumentException("SuperLoadingLayout need a successView to show");
        }

        if (getChildCount() > 1) {
            throw new IllegalStateException("SuperLoadingLayout can host only one direct child");
        }

        mSuccessView = getChildAt(0);

        addContentViews();

        // 将SuccessView置于顶端
        // mSuccessView.bringToFront();
    }

    /**
     * 依次添加加载中，加载失败及加载为空的View
     */
    private void addContentViews() {

        mLoadingView = View.inflate(UIUtils.getContext(), loadingViewRes, null);
        addView(mLoadingView);

        mEmptyView = View.inflate(UIUtils.getContext(), emptyViewRes, null);
        addView(mEmptyView);

        mErrorView = View.inflate(UIUtils.getContext(), errorViewRes, null);
        addView(mErrorView);

        mIvLoading = (ImageView) mLoadingView.findViewById(R.id.iv_loading);
        // 开启动画
        mDrawable = (AnimationDrawable) mIvLoading.getDrawable();

        // 重新加载数据
        RelativeLayout btnRetry = (RelativeLayout) findViewById(R.id.error_btn_retry);
        btnRetry.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    // 点击重试应该重新加载
                    refreshState(STATE_LOADING);
                    mListener.onStartLoadData();
                }
            }
        });

        mTvErrorState = (TextView) findViewById(R.id.tv_error_state);

        // 刷新布局
        refreshLayoutUI();
    }

    /**
     * 触发加载数据,<b>加载完成数据后需要手动调用如下方法刷新页面状态:</b>
     */
    public void triggerLoadData(OnStartLoadDataListener listener) {
        if (listener == null) {
            throw new NullPointerException("OnStartLoadDataListener can not be null,you must trigger the callback");
        }

        mListener = listener;

        //如果加载成功就不再重新自动加载.正在加载也不重新加载
        if (currentState != STATE_SUCCESS || currentState != STATE_LOADING) {
            // 重置当前的状态
            currentState = STATE_LOADING;
            refreshLayoutUI();

            listener.onStartLoadData();
        }
    }

    /**
     * 刷新Layout的状态，根据状态判定Layout显示什么布局
     */
    public void refreshState(@LoadState int state) {
        currentState = state;
        //刷新界面
        refreshLayoutUI();
    }

    private void refreshLayoutUI() {

        // 控制加载视图的显示/隐藏
        if ((currentState == STATE_LOADING)) {
            mLoadingView.setVisibility(VISIBLE);
            mDrawable.start();
        } else {
            mLoadingView.setVisibility(GONE);
            mDrawable.stop();
        }

        // 控制成功视图的显示/隐藏
        mSuccessView.setVisibility((currentState == STATE_SUCCESS) ? View.VISIBLE : View.GONE);
        // 控制空视图的显示/隐藏
        mEmptyView.setVisibility((currentState == STATE_EMPTY) ? View.VISIBLE : View.GONE);
        // 控制错误视图的显示/隐藏
        mErrorView.setVisibility((currentState == STATE_ERROR) ? View.VISIBLE : View.GONE);

        if (currentState == STATE_ERROR) {
            // 错误视图的分开显示（有、无网络）
            if (!NetworkUtils.isNetworkAvailable(UIUtils.getContext())) {
                Drawable drawable = getResources().getDrawable(R.mipmap.ic_net_error);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                mTvErrorState.setCompoundDrawables(null, drawable, null, null);
                mTvErrorState.setText(R.string.pager_net_error);
            } else {
                Drawable drawable = getResources().getDrawable(R.mipmap.ic_pager_error);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                mTvErrorState.setText(R.string.pager_reload);
                mTvErrorState.setCompoundDrawables(null, drawable, null, null);
            }
        }
    }

    @LoadState
    public int getCurrentState() {
        return currentState;
    }

    public interface OnStartLoadDataListener {
        void onStartLoadData();
    }
}
